from fastapi import FastAPI
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise

from app.config import config


class TortoiseProvider():
    # 配置 MySQL 数据库
    TORTOISE_ORM = {
        "connections": {
            "default": {
                "engine": "tortoise.backends.mysql",
                "credentials": {
                    "host": config.mysql.host,
                    "port": config.mysql.port,
                    "user": config.mysql.user,
                    "password": config.mysql.password,
                    "database": config.mysql.dbname,
                    "minsize": 1,
                    "maxsize": 5,
                    "charset": "utf8mb4",  # 编码
                    "echo": True  # 是否反馈SQL语句
                }
            }
        },
        "apps": {
            "models": {
                "models": ["app.models.userModel","aerich.models"],  # models数据模型迁移
                "default_connection": "default"
            }
        },
        "use_tz": False,
        "timezone": "Asia/Shanghai"
    }

    @classmethod
    async def init_tortoise(cls, app: FastAPI):
        """
        初始化tortoise
        """
        register_tortoise(app, config=cls.TORTOISE_ORM)

    @classmethod
    async def close_tortoise(cls):
        """
        关闭tortoise
        :return:
        """
        await Tortoise.close_connections()

# 到处给数据迁移工具使用
TORTOISE_ORM  = TortoiseProvider.TORTOISE_ORM